﻿using System;
using System.Net;
using System.Net.Sockets;

namespace Monitor.Core.Sensor
{
    class TcpSensor : AbstractSensor
    {
        public TcpSensor(int id, Uri uri)
            : base(id, uri)
        {
        }

        protected override ServiceStatus PingService()
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(this._uri.Host);

            foreach (IPAddress address in hostEntry.AddressList)
            {
                IPEndPoint ipe = new IPEndPoint(address, this._uri.Port);
                using (Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(ipe);
                    if (socket.Connected)
                    {
                        socket.Close();
                        return ServiceStatus.Alive;
                    }
                    else
                        continue;
                }
            }

            this._lastError = "Cannot connect";
            return ServiceStatus.Unknown;
        }
    }
}
